package com.project.card.ui;

import static com.project.card.util.UrlUtil.SERVER_URL;

import android.app.Dialog;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.card.R;
import com.project.card.adapter.GoodAdapter;
import com.project.card.bean.GoodBean;

import java.util.ArrayList;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MarketFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MarketFragment extends Fragment {
    private GridView gridView;
    private ArrayList<GoodBean> goodList=new ArrayList<>();
    private JsonNode nodeMarket;

    public static final ObjectMapper JSONMAPPER = new ObjectMapper()
            .enable(JsonParser.Feature.IGNORE_UNDEFINED)
            .enable(JsonParser.Feature.ALLOW_COMMENTS)
            .enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES)
            .enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES)
            .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public MarketFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MarketFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MarketFragment newInstance(String param1, String param2) {
        MarketFragment fragment = new MarketFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        OkHttpClient client = new OkHttpClient();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //Log.d("tnn","startf");
                    FormBody.Builder params = new FormBody.Builder();
                    params.add("id","1");
                    Request request = new Request.Builder()
                            .url(SERVER_URL+"market/list")
                            .post(params.build())
                            .build();
                    //Log.d("tnn","req");
                    Response response = client.newCall(request).execute();
                    //Log.d("tnn","res");
                    String responseData = response.body().string();
                    nodeMarket =JSONMAPPER.readTree(responseData);
                    nodeMarket.get("data").forEach(data -> {
                        GoodBean temp = new GoodBean();
                        temp.setTitle(data.get("title").asText());
                        temp.setPrice(data.get("price").asInt());
                        temp.setImage(R.drawable.ic_launcher_background);
                        //Log.d("tng",data.get("title").asText());
                        //Log.d("tng",data.get("price").asText());
                        goodList.add(temp);
                    });
                    //Log.d("tnn", responseData);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment_market,container,false);
        gridView=(GridView) view.findViewById(R.id.market_gridview);
        goodList.clear();


//        goodList.add(new GoodBean(1,"First",10,R.drawable.ic_launcher_background));

        GoodAdapter goodAdapter=new GoodAdapter(getActivity().getApplicationContext(),R.layout.good_item,goodList);
        gridView.setAdapter(goodAdapter);
        return view;
        //return inflater.inflate(R.layout.fragment_market, container, false);
    }
}